package com.photoeditor.demo.ui.dialog;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.common.base.ComponentContext;
import com.photoeditor.R;
import com.photoeditor.demo.model.event.FeedBackEvent;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.util.AppFrontBackHelper;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import static com.photoeditor.demo.ui.dialog.RateGuide.getEntrance;
import static com.photoeditor.demo.ui.dialog.RateGuide.getString;

public class VirtualRateGoodDialog extends BaseVirtualRateDialog implements View.OnClickListener {
    private static final int TIME_SHOW_ANIMATION = 900;
    private static final float ANIMATION_SCALE_LIMIT = 0.3f;

    private static VirtualRateGoodDialog sRateDialog;

    //        private RoundImageView mIcon;
    private ImageView mStar1, mStar2, mStar3, mStar4, mStar5;
    private ValueAnimator mStart1Animator, mStart2Animator, mStart3Animator, mStart4Animator, mStart5Animator;
    private LinearLayout mLayoutStars;
    //        private TextView mTvThank;
    private TextView mTvTitle;
    private List<String> mRateTexts;

    private ValueAnimator mShowAnimator;
    private String mEntrance;
    private boolean mIsNeedStatisticsClose = true;
    private Context mContext;

    private int mPos = -1;


    public static void showRateDialogVirtual(final Context context) {
        String entrance = getEntrance(context);

        sRateDialog = new VirtualRateGoodDialog(context);
        sRateDialog.setCanceledOnTouchOutside(true);
        sRateDialog.setOnShowListener(sRateDialog.createOnShowListener(entrance));
        sRateDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                //??
                AppFrontBackHelper.getInstant().setListener(null);
            }
        });
        sRateDialog.show();
    }

    public static final int MESSAGE_WHAT_RATE_FAKE_CLICK = 111;
    public static Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == MESSAGE_WHAT_RATE_FAKE_CLICK) {
                int star = (int) msg.obj;
                /*RateStrategyBean.RateStrategyBeanConfig config = getRateStrategyConfig();
                if(config != null && star >= config.getComStar()) {
                    gotoGPStoreOrBrowser(ComponentContext.getPackageName());
                    SPDataManager.setHasRated();
                    Toast.makeText(ComponentContext.getContext(), getString(R.string.toast_go_gp), Toast.LENGTH_SHORT).show();

                    EventBus.getDefault().post(new FeedBackEvent());
                } else */
                if (star >= 4) {
                    gotoGPStoreOrBrowser(ComponentContext.getPackageName());
                    SPDataManager.setHasRated();
                    Toast.makeText(ComponentContext.getContext(), getString(R.string.toast_go_gp), Toast.LENGTH_SHORT).show();
                    EventBus.getDefault().post(new FeedBackEvent());
                    DialogStatistic.rateGoodSub(RateGuide.getWhere());
                } else {
                    DialogStatistic.rateGoodClose((RateGuide.getWhere()));
                }
                if (sRateDialog != null) {
                    sRateDialog.setNeedStatisticsClose(false);
                    sRateDialog.dismiss();
                }
            }
        }
    };

    public static void gotoGPStoreOrBrowser(String packageName) {
        // 跳转到应用市场
        Intent intent = new Intent();
        try {
            intent.setAction(Intent.ACTION_VIEW);
            String appAddr = "market://details?id=" + packageName;
            intent.setData(Uri.parse(appAddr));
            intent.setPackage("com.android.vending");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentContext.getContext().startActivity(intent);
        } catch (ActivityNotFoundException | SecurityException e) {
            intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            String webAddr = "https://play.google.com/store/apps/details?id=" + packageName;
            intent.setData(Uri.parse(webAddr));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            try {
                ComponentContext.getContext().startActivity(intent);
            } catch (ActivityNotFoundException | SecurityException e1) {
                Toast.makeText(ComponentContext.getContext(), "sorry,your mobile can't be supported", Toast.LENGTH_LONG).show();
            }
        }
    }

    public void setNeedStatisticsClose(boolean needStatisticsClose) {
        mIsNeedStatisticsClose = needStatisticsClose;
    }

    @Override
    public void dismiss() {
        super.dismiss();
    }

    public VirtualRateGoodDialog(Context context) {
        super(context);
        mContext = context;
        mEntrance = getEntrance(context);
        setTvTitle();
    }

    @Override
    public void initDefaultView(final Context context) {
        super.initDefaultView(context);
        setContentView(R.layout.dialog_virtual_rate_good);
//            WindowManager.LayoutParams lp = this.getWindow().getAttributes();
//            lp.width = DeviceUtils.getScreenWidthPx();
//            lp.height = DeviceUtils.getScreenHeightPx();
//            this.getWindow().setAttributes(lp);
        mRateTexts = new ArrayList<>();
        mRateTexts.add(getString(R.string.rate_start_1));
        mRateTexts.add(getString(R.string.rate_start_2));
        mRateTexts.add(getString(R.string.rate_start_3));
        mRateTexts.add(getString(R.string.rate_start_4));
        mRateTexts.add(getString(R.string.rate_start_5));
//            mIcon = (RoundImageView) findViewById(R.id.iv_user_icon);
        //mIcon.setImageBitmap(ImageUtil.getTopRoundConnerBitmap(BitmapFactory.decodeResource(context.getResources(),R.drawable.rate_fake_banner),DeviceUtils.dip2px(AppApplication.getContext(),3)));
//            int radius = DeviceUtils.dip2px(getContext(), 3);
//            mIcon.setRadius(new float[]{radius, radius, radius, radius, 0, 0, 0, 0});
        mStar1 = (ImageView) findViewById(R.id.iv_star_1);
        mStar1.setOnClickListener(this);
        mStar2 = (ImageView) findViewById(R.id.iv_star_2);
        mStar2.setOnClickListener(this);
        mStar3 = (ImageView) findViewById(R.id.iv_star_3);
        mStar3.setOnClickListener(this);
        mStar4 = (ImageView) findViewById(R.id.iv_star_4);
        mStar4.setOnClickListener(this);
        mStar5 = (ImageView) findViewById(R.id.iv_star_5);
        mStar5.setOnClickListener(this);

        mLayoutStars = findViewById(R.id.layout_stars);
//            mTvThank = findViewById(R.id.tv_thanks);
        mTvTitle = findViewById(R.id.tv_rate);

//        findViewById(R.id.cancel).setOnClickListener(this);
//        findViewById(R.id.sure).setOnClickListener(this);

        DialogStatistic.rateGoodShow(RateGuide.getWhere());
    }

    private void setTvTitle() {
        String s = getContext().getString(R.string.dialog_virtual_good_title);
        mTvTitle.setText(s);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_star_1:
                mStar1.setSelected(true);
                mStar2.setSelected(false);
                mStar3.setSelected(false);
                mStar4.setSelected(false);
                mStar5.setSelected(false);
                mPos = 0;
                break;
            case R.id.iv_star_2:
                mStar1.setSelected(true);
                mStar2.setSelected(true);
                mStar3.setSelected(false);
                mStar4.setSelected(false);
                mStar5.setSelected(false);
                mPos = 1;
                break;
            case R.id.iv_star_3:
                mStar1.setSelected(true);
                mStar2.setSelected(true);
                mStar3.setSelected(true);
                mStar4.setSelected(false);
                mStar5.setSelected(false);
                mPos = 2;
                break;
            case R.id.iv_star_4:
                mStar1.setSelected(true);
                mStar2.setSelected(true);
                mStar3.setSelected(true);
                mStar4.setSelected(true);
                mStar5.setSelected(false);
                mPos = 3;
                break;
            case R.id.iv_star_5:
                mStar1.setSelected(true);
                mStar2.setSelected(true);
                mStar3.setSelected(true);
                mStar4.setSelected(true);
                mStar5.setSelected(true);
                mPos = 4;
                break;
//            case R.id.cancel:
//                if (mListener != null && mListener.get() instanceof IRateDialogListener) {
//                    ((IRateDialogListener) mListener.get()).onCloseClick();
//                }
//                mPos = -1;
//                sendMessage();
//                DialogStatistic.rateGoodClose(RateGuide.getWhere());
//                break;
//            case R.id.sure:
//                if (mListener != null && mListener.get() instanceof IRateDialogListener) {
//                    ((IRateDialogListener) mListener.get()).onScoreClick(mPos);
//                }
//                sendMessage();
//                DialogStatistic.rateGoodSub(RateGuide.getWhere());
            default:
                break;
        }
        if (mListener != null && mListener.get() instanceof IRateDialogListener) {
            ((IRateDialogListener) mListener.get()).onScoreClick(mPos);
        }
        sendMessage();
    }

    private void sendMessage() {
        Message message = Message.obtain();
        message.what = MESSAGE_WHAT_RATE_FAKE_CLICK;
        message.obj = mPos + 1;
        mHandler.sendMessage(message);
//            mHandler.sendMessageDelayed(message, 500);
    }

    @Override
    public void onBackPressed() {
        if (mShowAnimator != null && mShowAnimator.isRunning()) {
            mShowAnimator.cancel();
            mShowAnimator = null;
        }
        setOnShowListener(null);
        DialogStatistic.rateGoodClose(RateGuide.getWhere());
        super.onBackPressed();
    }

    protected OnShowListener createOnShowListener(final String entrance) {
        return new OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                getShowAnimator().start();
                AppFrontBackHelper.getInstant().setListener(new AppFrontBackHelper.OnAppStatusListener() {
                    boolean isFirLeave = true;

                    @Override
                    public void onFront() {

                    }

                    @Override
                    public void onBack() {
                        if (isFirLeave) {
                            isFirLeave = false;
                        }
                    }
                });
            }
        };
    }

    private void initStar1Animator() {
        if (mStart1Animator == null) {
            mStart1Animator = ValueAnimator.ofFloat(0, 1);
            mStart1Animator.setDuration(TIME_SHOW_ANIMATION);
            mStart1Animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();
                    float ratio = 0;
                    if (value <= 0.5) {
                        ratio = value / 0.5f;
                        mStar1.setScaleX((float) (1 + ratio * ANIMATION_SCALE_LIMIT));
                        mStar1.setScaleY((float) (1 + ratio * ANIMATION_SCALE_LIMIT));
                    } else {
                        ratio = (float) ((value - 0.5) / 0.5);
                        mStar1.setScaleX((float) (1 + ANIMATION_SCALE_LIMIT - ANIMATION_SCALE_LIMIT * ratio));
                        mStar1.setScaleY((float) (1 + ANIMATION_SCALE_LIMIT - ANIMATION_SCALE_LIMIT * ratio));
                    }
                }
            });
        }
    }

    private void initStar2Animator() {
        if (mStart2Animator == null) {
            mStart2Animator = ValueAnimator.ofFloat(0, 1);
            mStart2Animator.setDuration(TIME_SHOW_ANIMATION);
            mStart2Animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();
                    float ratio = 0;
                    if (value <= 0.5) {
                        ratio = value / 0.5f;
                        mStar2.setScaleX((float) (1 + ratio * ANIMATION_SCALE_LIMIT));
                        mStar2.setScaleY((float) (1 + ratio * ANIMATION_SCALE_LIMIT));
                    } else {
                        ratio = (float) ((value - 0.5) / 0.5);
                        mStar2.setScaleX((float) (1 + ANIMATION_SCALE_LIMIT - ANIMATION_SCALE_LIMIT * ratio));
                        mStar2.setScaleY((float) (1 + ANIMATION_SCALE_LIMIT - ANIMATION_SCALE_LIMIT * ratio));
                    }
                }
            });
        }
    }

    private void initStar3Animator() {
        if (mStart3Animator == null) {
            mStart3Animator = ValueAnimator.ofFloat(0, 1);
            mStart3Animator.setDuration(TIME_SHOW_ANIMATION);
            mStart3Animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();
                    float ratio = 0;
                    if (value <= 0.5) {
                        ratio = value / 0.5f;
                        mStar3.setScaleX((float) (1 + ratio * ANIMATION_SCALE_LIMIT));
                        mStar3.setScaleY((float) (1 + ratio * ANIMATION_SCALE_LIMIT));
                    } else {
                        ratio = (float) ((value - 0.5) / 0.5);
                        mStar3.setScaleX((float) (1 + ANIMATION_SCALE_LIMIT - ANIMATION_SCALE_LIMIT * ratio));
                        mStar3.setScaleY((float) (1 + ANIMATION_SCALE_LIMIT - ANIMATION_SCALE_LIMIT * ratio));
                    }
                }
            });
        }
    }

    private void initStar4Animator() {
        if (mStart4Animator == null) {
            mStart4Animator = ValueAnimator.ofFloat(0, 1);
            mStart4Animator.setDuration(TIME_SHOW_ANIMATION);
            mStart4Animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();
                    float ratio = 0;
                    if (value <= 0.5) {
                        ratio = value / 0.5f;
                        mStar4.setScaleX((float) (1 + ratio * ANIMATION_SCALE_LIMIT));
                        mStar4.setScaleY((float) (1 + ratio * ANIMATION_SCALE_LIMIT));
                    } else {
                        ratio = (float) ((value - 0.5) / 0.5);
                        mStar4.setScaleX((float) (1 + ANIMATION_SCALE_LIMIT - ANIMATION_SCALE_LIMIT * ratio));
                        mStar4.setScaleY((float) (1 + ANIMATION_SCALE_LIMIT - ANIMATION_SCALE_LIMIT * ratio));
                    }
                }
            });
        }
    }

    private void initStar5Animator() {
        if (mStart5Animator == null) {
            mStart5Animator = ValueAnimator.ofFloat(0, 1);
            mStart5Animator.setDuration(TIME_SHOW_ANIMATION);
            mStart5Animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();
                    float ratio = 0;
                    if (value <= 0.5) {
                        ratio = value / 0.5f;
                        mStar5.setScaleX((float) (1 + ratio * ANIMATION_SCALE_LIMIT));
                        mStar5.setScaleY((float) (1 + ratio * ANIMATION_SCALE_LIMIT));
                    } else {
                        ratio = (float) ((value - 0.5) / 0.5);
                        mStar5.setScaleX((float) (1 + ANIMATION_SCALE_LIMIT - ANIMATION_SCALE_LIMIT * ratio));
                        mStar5.setScaleY((float) (1 + ANIMATION_SCALE_LIMIT - ANIMATION_SCALE_LIMIT * ratio));
                    }
                }
            });
        }
    }

    private Animator getShowAnimator() {
        if (mShowAnimator == null) {
            mShowAnimator = ValueAnimator.ofFloat(0, 1f);
            mShowAnimator.setDuration(TIME_SHOW_ANIMATION);
            mShowAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float ratio = animation.getAnimatedFraction();
                    if (ratio > 0 && ratio <= 0.2f) {
                        if (mStart1Animator == null) initStar1Animator();
                        if (!mStart1Animator.isRunning()) mStart1Animator.start();
                        mStar1.setSelected(true);
                    } else if (ratio > 0.2 && ratio <= 0.4) {
                        if (mStart2Animator == null) initStar2Animator();
                        if (!mStart2Animator.isRunning()) mStart2Animator.start();
                        mStar2.setSelected(true);
                    } else if (ratio > 0.4 && ratio <= 0.6) {
                        if (mStart3Animator == null) initStar3Animator();
                        if (!mStart3Animator.isRunning()) mStart3Animator.start();
                        mStar3.setSelected(true);
                    } else if (ratio > 0.6 && ratio <= 0.8) {
                        if (mStart4Animator == null) initStar4Animator();
                        if (!mStart4Animator.isRunning()) mStart4Animator.start();
                        mStar4.setSelected(true);
                    } else if (ratio > 0.8 && ratio <= 1) {
                        if (mStart5Animator == null) initStar5Animator();
                        if (!mStart5Animator.isRunning()) mStart5Animator.start();
                        mStar5.setSelected(true);
                    }
                }
            });
            mShowAnimator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    initStar1Animator();
                    initStar2Animator();
                    initStar3Animator();
                    initStar4Animator();
                    initStar5Animator();
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    for (int i = 0; i < mLayoutStars.getChildCount(); i++) {
                        View child = mLayoutStars.getChildAt(i);
                        child.setSelected(false);
                    }
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                    for (int i = 0; i < mLayoutStars.getChildCount(); i++) {
                        View child = mLayoutStars.getChildAt(i);
                        child.setSelected(false);
                    }
                }

                @Override
                public void onAnimationRepeat(Animator animation) {
                }
            });
        }
        return mShowAnimator;
    }

}